﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.IdentityModel.Tokens;
using RxxAdmin.Common;
using RxxAdmin.Common.Helper;
using RxxAdmin.Common.HttpContextUser;
using RxxAdmin.Common.Hubs;
using RxxAdmin.Extensions.Cache;
using RxxAdmin.IServices;
using RxxAdmin.Model;
using RxxAdmin.Services;
using Serilog;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using static RxxAdmin.Common.AppSettings;
using static RxxAdmin.Model.CustomApiVersion;

namespace RxxAdmin.Api.Controllers;

/// <summary>
/// 测试
/// </summary>
public class TestController : BaseApiController
{
    private readonly ICacheService _cacheService;
    private readonly IHubContext<ChatHubb> _hubContext;
    private readonly IUser _user;

    public TestController(ICacheService cacheService,IHubContext<ChatHubb> hubContext,IUser user)
    {
        _cacheService = cacheService;
        _hubContext = hubContext;
        _user = user;
    }
    /// <summary>
    /// 测试获取
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    //[AllowAnonymous]
    public async Task<MessageModel<DateTime>> Get()
    {        
        await Task.CompletedTask;

        await _hubContext.Clients.All.SendAsync("ReceiveMessage", "你好", "世界！");

        var a = HubState.Users;
        //测试Serilog日志
        //Log.Information(AppSettings.ApiName);
        //Log.Information(AppSettings.app(new string[] { "Startup", "ApiName" }));
        //测试Redis缓存
        //_cacheService.Add("rxx", "ruxingxing");
        //return Success("Hello World");
        return Success(DateTime.Now, "Hello World " + _user.Name);
    }   
    [HttpGet]
    [ApiExplorerSettings(GroupName = nameof(CustomApiVersion.ApiVersions.V1))]
    public async Task<MessageModel<DateTime>> GetV1() {
        await Task.CompletedTask;       
        return Success(DateTime.Now, "Hello World V1");
    }
    [HttpGet]
    [ApiExplorerSettings(GroupName = nameof(CustomApiVersion.ApiVersions.V2))]
    public async Task<MessageModel<DateTime>> GetV2()
    {
        await Task.CompletedTask;       
        return Success(DateTime.Now, "Hello World V2");
    }
    [HttpGet]
    [ApiExplorerSettings(GroupName = nameof(CustomApiVersion.ApiVersions.V3))]
    public async Task<MessageModel<DateTime>> GetV3()
    {
        await Task.CompletedTask;
        return Success(DateTime.Now, "Hello World V3");
    }
    /// <summary>
    /// 获取Token
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    public async Task<MessageModel> GetToken(string username,string password)
    {
        await Task.CompletedTask;
        // 1. 定义需要使用到的Claims
        var claims = new[]
        {
            new Claim("name", username),
            /* 可以保存自己想要信息，传参进来即可
            new Claim("sex", "sex"),
            new Claim("limit", "limit"),
            new Claim("head_url", "xxxxx")
            */
        };
        // 2. 从 appsettings.json 中读取SecretKey
        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Jwt.SecretKey));
        // 3. 选择加密算法
        var algorithm = SecurityAlgorithms.HmacSha256;
        // 4. 生成Credentials
        var signingCredentials = new SigningCredentials(secretKey, algorithm);
        // 5. 根据以上，生成token
        var jwtSecurityToken = new JwtSecurityToken(
            Jwt.Issuer,    //Issuer
            Jwt.Audience,  //Audience
            claims,                          //Claims,
            DateTime.Now,                    //notBefore
            DateTime.Now.AddDays(30),     //expires
            signingCredentials               //Credentials
        );
        // 6. 将token变为string
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        return Success(token);
    }

    [HttpGet]
    public async Task<object> GetEntity()
    {
        await Task.CompletedTask;
        return "";
    }
    /// <summary>
    /// 测试 MD5 加密字符串
    /// </summary>
    /// <param name="password"></param>
    /// <returns></returns>
    [HttpGet]
    [Route("Md5Password")]
    public string Md5Password(string password = "")
    {
        Log.Information("asdasdasd");
        return MD5Helper.MD5Encrypt32(password);
    }
}
